<template>
  <div class="cart">
    <van-nav-bar title="购物袋" /><!-- left-arrow -->
    <!-- 遍历 -->
    <ul v-if="token && list.length">
      <div class="goods-list" v-for="data in list" :key="data._id">
        <div class="goods">
          <van-checkbox v-model="data.checked"></van-checkbox>
          <img :src="data.product.coverImg" alt="" class="data_img" />
          <div class="good-info" style="width: 120px">
            <p class="data_name">{{ data.product.name }}</p>
            <!-- 步进器 -->
            <div class="operation">
              <span
                @click="data.quantity > 1 && updatePro(data.product._id, -1)"
                >-</span
              >
              {{ data.quantity }}
              <span @click="updatePro(data.product._id, 1)">+</span>
            </div>
          </div>
          <div class="caozuo">
            <van-icon name="ellipsis" @click="del(data._id)" />
            <div class="kongbai"></div>
            <p class="data_price">
              ￥{{ (data.product.price / 100).toFixed(2) }}
            </p>
          </div>
        </div>
      </div>
    </ul>

    <!-- 购物车是空 -->
    <div class="goods_none" v-if="!list.length && token">
      <h1>你的购物车是空的</h1>
      <p>你可以通过搜索或浏览商品的方式将商品添加到购物车中</p>
      <button class="goshopping" @click="gohome">前去购物</button>
    </div>

    <!--没有登录  -->
    <div class="token_none" v-if="!token">
      <div class="outer_box">
        <div class="outer">登录 <span class="span_entry">宜家</span> 账户</div>
        <p>{{ token }}</p>
        <p>查看购物车中的商品</p>
        <button class="gologin" @click="gologin">前去登录</button>
      </div>
    </div>

    <!-- 全选 -->
    <van-submit-bar
      v-if="list.length && token"
      :price="sumPrice"
      button-color="#004f93"
      button-text="结算"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checked" />
      全选
      <van-icon name="delete-o" @click="dels" />
    </van-submit-bar>
  </div>
</template>

<script>
import {
  getCartdate,
  delmanyCart,
  delCartdate,
  addorder,
  addTocart,
} from "../../api/cart";

import { Toast } from "vant";
import { getToken } from "../../utils/setCookie";
import { getAddresslistApi } from "../../api/address";
import { Dialog } from "vant";
export default {
  data() {
    return {
      list: [],
      token: getToken("token"),
      userAddress: {},
      ids: [],
      value: 1,
      page: 1,
      isDefault: [],
      selectlist: [],
      cartids: [],
    };
  },
  computed: {
    //全选不全选
    checked: {
      set(flag) {
        return this.list.map((item) => this.$set(item, "checked", flag));
      },
      get() {
        return (
          this.list.length ===
          this.list.filter((item) => item.checked == true).length
        );
      },
    },

    //计算总价
    sumPrice() {
      return this.list
        .filter((item) => {
          return item.checked;
        })
        .reduce(function (pre, cur) {
          return (pre += cur.product.price * cur.quantity);
        }, 0);
    },

    //批量删除
    selectgoods() {
      this.list.forEach((item) => {
        if (item.checked) {
          this.selectlist.push({
            quantity: item.quantity,
            price: item.product.price,
            product: item.product._id, //商品id，后期可以拿到具体的商品
          });
          this.cartids.push(item._id); //如果选中的话，就往cartids里加购物车id，
        }
      });
      return this.selectlist;
    },
  },
  watch: {},
  methods: {
    //步进器
    async updatePro(id, value) {
      await addTocart(id, value); //调用添加接口
      //同时页面需要同步2种方法  循环list列表，重新掉接口
      this.list.forEach((data) => {
        //如果传进来的id等于商品id
        if (data.product._id == id) {
          data.quantity = data.quantity + value;
        }
      });
    },
    //购物车是空的时候，点击按钮跳转首页
    gohome() {
      this.$router.push("/home");
    },
    gologin() {
      this.$router.push("/login");
    },
    //获取购物车列表
    async getCartlist() {
      const result = await getCartdate();
      // console.log(result);
      this.list = result;
    },
    //删除商品
    del(id) {
      Dialog.confirm({
        title: "删除",
        message: "确定删除？",
      })
        .then(async () => {
          await delCartdate(id);
          Toast("已删除该商品");
          this.getCartlist();
        })
        .catch(() => {});
    },
    //删除多个购物车
    async dels() {
      // var arr = [];
      this.selectgoods.forEach((item) => {
        // arr.push(item.product);
        console.log(item);
      });
      // this.ids = arr;
      //批量删除的时候，直接把购物车里的勾选的id，删除
      const result = await delmanyCart({ ids: this.cartids });
      if (result.n > 0) {
        this.getCartlist();
      } else {
        Toast("还没有选中商品哦");
      }
    },
    //读取收货地址
    async getAddresses() {
      const result = await getAddresslistApi({
        page: this.page,
      });
      result.addresses.forEach((address) => {
        if (address.isDefault === true) {
          this.userAddress = address;
        } else {
          this.isDefault.push(address.isDefault);
          const flag = this.isDefault.every((v) => v === false);
          if (flag === false) {
            this.userAddress = result.addresses[0];
          }
        }
      });
    },
    //提交订单
    async onSubmit() {
      if (this.selectgoods.length > 0) {
        this.getAddresses(this.userAddress);
        if (this.userAddress) {
          const result = await addorder({
            receiver: this.userAddress.receiver,
            regions: this.userAddress.regions,
            address: this.userAddress.address,
            orderDetails: this.selectgoods,
          });
          console.log(result);
          if (result.code === "success") {
            // Toast('提交成功');
            this.dels();
            this.getCartlist();
            // let id = "123";
            this.$router.push({
              name: "OrderList",
              // path: "/orderlist/" + id,

              params: { ids: [result.info.order._id] },
              // params: { ids: [123] },
            });
            // this.$router.push("/orderlist");
          }
        } else {
          // this.$router.push("/addaddr");
        }
      } else {
        // console.log(this.selectgoods.length);
        Toast("还没有选择商品哦");
      }
    },
  },
  created() {
    this.getCartlist();
  },
  mounted() {},
  components: {},
};
</script>

<style scoped>
.shop_bag {
  width: 100%;
  font-weight: 800;
  font-size: 25px;
  position: absolute;
  text-align: center;
  top: 0;
  padding: 10px 0;
  border-bottom: 1px solid rgb(241, 241, 241);
}
.cart {
  padding-bottom: 50px;
}
.goods {
  width: 100%;
  height: 120px;
  align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.data_img {
  width: 70px;
  height: 70px;
}
.data_name {
  font-size: 13px;
  line-height: 18px;
  font-weight: 800;
}
.data_desc {
  font-size: 13px;
  line-height: 18px;
  color: #484848;
  margin-top: 5px;
}
.operation {
  width: 80px;
  height: 30px;
  border-radius: 30px;
  border: 1px solid #ccc;
  line-height: 30px;
  display: flex;
  flex-direction: row;
  margin-top: 5px;
  justify-content: space-around;
}
.stepper {
  margin-top: 5px;
}
.popup {
  height: 100px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.showPopup_span {
  font-weight: 800;
}
.goods_none {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-left: 50px;
  margin-top: 100px;
}
.goods_none h1 {
  font-size: 22px;
  font-weight: 800;
  margin-bottom: 30px;
}
.goods_none p {
  font-size: 13px;
  font-weight: 400;
}
.goshopping {
  margin-top: 30px;
  width: 200px;
  height: 50px;
  border-radius: 50px;
  background-color: #004f93;
  border: 1px solid #004f93;
  color: #fff;
  font-size: 12px;
}
.outer_box {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: flex-start;
}
.outer {
  font-weight: 800;
  font-size: 20px;
  margin-top: 100px;
  line-height: 30px;
  color: #111;
  padding-left: 17px;
}
.span_entry {
  color: #0058a3;
  cursor: pointer;
  font-weight: 800;
}
.outer_box p {
  font-size: 13px;
  line-height: 20px;
  color: #111;
  margin-top: 20px;
  padding-left: 17px;
}
.gologin {
  margin-top: 20px;
  margin-left: 17px;
  width: 200px;
  height: 55px;
  background: #0058a3;
  border-radius: 27px;
  font-size: 14px;
  line-height: 22px;
  color: #fff;
  outline: 0;
  border: 0;
}

.van-submit-bar {
  bottom: 50px;
}
.caozuo {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-end;
}
.kongbai {
  height: 30px;
}
.van-icon-ellipsis {
  top: 0;
}
</style>
